import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers["X-Token"] = getToken();
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    if (response.status >= 200 && response.status < 300) {
      return response.data;
    }
    // 处理HTTP错误码
    Message({
      message: `服务异常：${response.status}`,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(new Error(`HTTP错误：${response.status}`));
  },
  (error) => {
    console.log("err" + error); // for debug
    let message = "请求异常";
    if (error.response) {
      console.error("HTTP错误详情:", {
        status: error.response.status,
        headers: error.response.headers,
        data: error.response.data,
      });
      message = `服务异常：${error.response.status}`;
    } else if (error.message.includes("timeout")) {
      message = "请求超时，请检查网络连接";
    } else if (error.message.includes("Network Error")) {
      message = "网络连接异常，请检查网络设置";
    } else {
      message = "接口请求失败，请稍后重试";
    }
    console.error("请求异常详情:", {
      url: error.config?.url,
      method: error.config?.method,
      params: error.config?.params,
      error: error.message,
    });
    Message({
      message: message,
      type: "error",
      duration: 5 * 1000,
    });

    // 新增HTTP状态码处理
    if (error.response) {
      switch (error.response.status) {
        case 404:
          message = "请求资源不存在";
          break;
        case 500:
          message = "服务器内部错误";
          break;
        case 401:
          message = "身份验证失败，请重新登录";
          break;
      }
    }
    return Promise.reject(error);
  }
);

export default service;
